package org.lx.nursing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.lx.common.utils.DateUtils;
import org.lx.nursing.domain.NursingLevel;
import org.lx.nursing.mapper.NursingLevelMapper;
import org.lx.nursing.service.INursingLevelService;
import org.lx.nursing.vo.NursingLevelVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NursingLevelServiceImpl extends ServiceImpl<NursingLevelMapper, NursingLevel> implements INursingLevelService {
    private static final String CACHE_KEY_PREFIX = "nursingLevel:all";

    @Autowired
    private NursingLevelMapper nursingLevelMapper;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public NursingLevel selectNursingLevelById(Long id) {
        return nursingLevelMapper.selectById(id);
    }

    @Override
    public List<NursingLevel> selectNursingLevelList(NursingLevel nursingLevel) {
        return nursingLevelMapper.selectNursingLevelList(nursingLevel);
    }

    @Override
    public int insertNursingLevel(NursingLevel nursingLevel) {
        nursingLevel.setCreateTime(DateUtils.getNowDate());
        int i = nursingLevelMapper.insertNursingLevel(nursingLevel);
        redisTemplate.delete(CACHE_KEY_PREFIX);
        return i;
    }

    @Override
    public int updateNursingLevel(NursingLevel nursingLevel) {
        nursingLevel.setUpdateTime(DateUtils.getNowDate());
        int i = nursingLevelMapper.updateNursingLevel(nursingLevel);
        redisTemplate.delete(CACHE_KEY_PREFIX);
        return i;
    }

    @Override
    public int deleteNursingLevelByIds(Long[] ids) {
        int i = nursingLevelMapper.deleteNursingLevelByIds(ids);
        redisTemplate.delete(CACHE_KEY_PREFIX);
        return i;
    }

    @Override
    public int deleteNursingLevelById(Long id) {
        return nursingLevelMapper.deleteById(id);
    }

    @Override
    public List<NursingLevelVo> selectNursingLevelVoList(NursingLevel nursingLevel) {
        return nursingLevelMapper.selectNursingLevelVoList(nursingLevel);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<NursingLevel> listAll() {
        List<NursingLevel> list = (List<NursingLevel>) redisTemplate.opsForValue().get(CACHE_KEY_PREFIX);
        if (list != null && !list.isEmpty()) return list;
        LambdaQueryWrapper<NursingLevel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NursingLevel::getStatus, 1);
        list = list(queryWrapper);
        redisTemplate.opsForValue().set(CACHE_KEY_PREFIX, list);
        return list;
    }
}
